package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var code int

// 查询用户是否存在
func UserExist(c *gin.Context) {

}

// 添加用户
func AddUser(c *gin.Context) {
	var data model.User
	var msg string
	var validCode int
	_ = c.ShouldBindJSON(&data)
	// 验证用户信息
	msg, validCode = validator.Validate(&data)
	if validCode != errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"status":  validCode,
			"message": msg,
		})
		c.Abort()
		return // 不执行后面的代码
	}
	code := model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		code = model.CreateUser(&data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		code = errmsg.ERROR_USERNAME_USED
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询单个用户
func GetUser(ctx *gin.Context) {
	var maps = make(map[string]interface{})
	id, _ := strconv.Atoi(ctx.Param("id"))
	data, code := model.GetUser(id)
	maps["id"] = id
	maps["username"] = data.Username
	maps["role"] = data.Role
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    maps,
		"total":   1,
		"message": errmsg.GetErrMsg(code),
	})

}

// 查询用户列表
func GetUserList(ctx *gin.Context) {
	// strconv.Atoi 字符串转换成 int
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}

	if pageNum == 0 {
		pageNum = 1
	}

	//if pageSize == 0 {
	//	pageSize = -1 //因gorm提供 一个方法
	//}
	//if pageNum == 0 {
	//	pageNum = -1 //因gorm提供 一个方法
	//}
	userList, total := model.GetUserList(pageSize, pageNum)
	fmt.Println("userList", userList)
	fmt.Println("total", total)
	code = errmsg.SUCCESS
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    userList,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})

}

// 修改用户
func EditUser(c *gin.Context) {
	var data model.User
	// 获取需要编辑用户的id
	id, _ := strconv.Atoi(c.Param("id"))
	// 前端的json数据绑定到用户模型上
	c.ShouldBindJSON(&data)
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		model.EditUser(id, &data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"data":    "数据删除成功！",
	})
}
